Yii2 Captcha is a built-in feature that provides a simple and effective way to prevent bots from submitting forms on your website. It generates and displays an image or audio challenge, which users must correctly interpret and enter to proceed with their form submission. This tutorial will guide you through the process of integrating and configuring Yii2 Captcha in your application.
To begin using Yii2 Captcha, make sure you have a working Yii2 application set up. If you haven't already, install Yii2 by following the official documentation. Once your application is ready, you can proceed with installing the Yii2 Captcha extension.
```
composer require --prefer-dist yiisoft/yii2-captcha
```
```php
'components' => [
// ...
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
],
// ...
],
```
Now that Yii2 Captcha is installed and configured, you can easily add it to your forms. To demonstrate, let's add Captcha validation to the user registration form.
```php
use yii\widgets\ActiveForm;
use yii\helpers\Html;
// Form widget with Captcha
echo $form->field($model, 'username')->textInput();
echo $form->field($model, 'email')->textInput();
echo $form->field($model, 'password')->passwordInput();
```
```php
use yii\web\Controller;
use app\models\RegistrationForm;
class SiteController extends Controller
{
public function actionRegister()
{
$model = new RegistrationForm();
// Registration logic here (e.g., save user to the database)
// ...
return $this->redirect(['site/login']);
}
return $this->render('register', ['model' => $model]);
}
}
```
By following these guidelines, you can effectively protect your Yii2 web application from spam and automated bot attacks using the Yii2 Captcha feature.